<template>
    <div>
        <div style="margin-bottom: 20px; text-align: left; margin-top: 20px;">
            <el-form>
                <el-button @click="deleteSome()" type="danger" size="mini" icon="el-icon-delete">批量删除</el-button>
                <el-input v-model="usernameLike" size="mini" placeholder="请输入用户名" style="margin-left: 20px; width: 200px; margin-right: 10px;"></el-input>
                <el-select v-model="userroleLike" size="mini" placeholder="请选择职位" style="width: 200px; margin-right: 10px;">
                    <el-option v-for="role in roleList" :key="role.id" :label="role.rolename" :value="role.id"></el-option>
                </el-select>
                <el-button size="mini" type="primary" icon="el-icon-search" @click="selectLike()">查 询</el-button>
                <el-button size="mini" type="primary" @click="clear()">清 空</el-button>
                <el-button size="mini" type="primary" @click="regFormVisible = true">新 增</el-button>
            </el-form>
        </div>
        <el-table :data="userList" border stripe style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50">
            </el-table-column>
            <el-table-column prop="id" label="编号" width="70">
            </el-table-column>
            <el-table-column prop="username" label="用户名" width="150">
            </el-table-column>
            <el-table-column prop="password" label="密码" width="150">
                <template slot-scope="scope">
                    <el-button @click="resetPassword(scope.row.id)" type="danger" size="mini" icon="el-icon-refresh-right">重置密码</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="真实姓名" width="120">
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="200">
            </el-table-column>
            <el-table-column prop="rolename" label="职位" width="120">
            </el-table-column>
            <el-table-column prop="createtime" label="创建时间" width="150">
            </el-table-column>
            <el-table-column prop="updatetime" label="修改时间" width="150">
            </el-table-column>
            <el-table-column label="操作" width="270">
                <template slot-scope="scope">
                    <el-button size="mini" @click="showAssignRole(scope.row.id)" icon="el-icon-edit">角色分配</el-button>
                    <el-button @click="deleteOne(scope.row.id)" type="danger" size="mini" icon="el-icon-delete">删 除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row>
            <el-col :span="20">
                <div class="pagination" style="margin-top: 20px; text-align: center;">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageInfo.pageNum" :page-sizes="[8, 15, 30, 50]" :page-size="pageInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>

        <el-dialog title="角色分配" :visible.sync="dialogVisible" width="37%">
            <el-transfer :props="{
                key: 'id',
                label: 'rolename'
            }" @change="onlyYou" v-model="assignRoleList" :data="roleList" :titles="['未分配角色', '已分配角色']" style="text-align: left;"></el-transfer>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateAssignRole()">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="新增用户" :visible.sync="regFormVisible" style="margin-left: 20%; width: 65%;">
            <el-row>
                <el-col :span="20" :offset="2">
                    <el-form :rules="rules" ref="regUser" :model="regUser" label-width="80px" style="margin-top: 30px;">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="regUser.username"></el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input v-model="regUser.password" type="password"></el-input>
                        </el-form-item>
                        <el-form-item label="真实姓名" prop="name">
                            <el-input v-model="regUser.name"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="regUser.phone"></el-input>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <div slot="footer">
                <el-button @click="regFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="register();">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            roleList: [],
            assignId: '',
            usernameLike: '',
            userroleLike: '',
            assignRoleList: [],
            checkList: [],
            dialogVisible: false,
            userList: [],
            pageInfo: {
                pageNum: 1,
                pageSize: 8
            },
            regUser: {},
            regFormVisible: false,
            rules: {
                username: [
                    { required: true, message: "用户名不能为空", trigger: "blur" },
                    { min: 3, max: 18, message: '密码长度在 3 到 18 个字符', trigger: "blur" },
                ],
                password: [
                    { required: true, message: "密码不能为空", trigger: "blur" },
                    { min: 3, max: 18, message: '密码长度在 3 到 18 个字符', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: "姓名不能为空", trigger: "blur" },
                    { min: 1, max: 10, message: '姓名长度在 1 到 10 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: "手机号不能为空", trigger: "blur" },
                    { min: 11, max: 11, message: '手机号长度为 11 位', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        register() {
            this.$refs.regUser.validate((valid) => {
                if (valid) {
                    this.$axios.post("/user/register", this.regUser)
                        .then((result) => {
                            if (result.data.code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.data.message
                                });
                                this.regFormVisible = false;
                                this.regUser = {
                                    username: '',
                                    password: '',
                                    name: '',
                                    phone: ''
                                };
                            } else {
                                this.$message.error(result.data.message);
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        })
                } else {
                    this.$message.error("请正确填写信息");
                }
            });
        },
        onlyYou(newValue) {
            if (newValue.length > 1) {
                this.assignRoleList = [newValue[newValue.length - 1]];
            }
        },
        updateAssignRole() {
            if (this.assignRoleList.length == 0) {
                this.$message.error("请选择一个职位");
            } else {
                this.$axios.get("/role/updateRoleList/" + this.assignId + "," + this.assignRoleList)
                    .then((result) => {
                        if (result.data.code == 200) {
                            this.$message({
                                type: 'success',
                                message: result.data.message
                            });
                            let i = result.data.data;
                            this.assignRoleList.push(i);
                            this.dialogVisible = false;
                            this.showList();
                        } else {
                            this.$message.error(result.data.message);
                        }
                    }).catch((err) => {
                        console.log(err);
                    });
            }
        },
        showAssignRole(id) {
            this.assignId = id;
            this.assignRoleList = [];
            this.$axios.get("/role")
                .then((result) => {
                    if (result.data.code == 200) {
                        this.roleList = result.data.data.list;
                    }
                }).catch((err) => {
                    console.log(err);
                });
            this.$axios.get("/role/selectRole?id=" + id)
                .then((result) => {
                    if (result.data.code == 200) {
                        let i = result.data.data;
                        this.assignRoleList.push(i);
                    }
                }).catch((err) => {
                    console.log(err);
                });
            this.dialogVisible = true;
        },
        clear() {
            this.usernameLike = '';
            this.userroleLike = '';
            this.showList();
        },
        selectLike() {
            if (this.userroleLike == '') {
                this.$message(
                    {
                        type: 'warning',
                        message: '请选择职位'
                    }
                );
            } else {
                this.$axios.get("/user/selectLike/" + this.pageInfo.pageNum + "," + this.pageInfo.pageSize + "," + this.usernameLike + "," + this.userroleLike)
                    .then((result) => {
                        this.$message({
                            type: 'success',
                            message: result.data.message
                        });
                        if (result.data.code == 200) {
                            this.pageInfo = result.data.data;
                            this.userList = result.data.data.list;
                            for (let i = 0; i < this.userList.length; i++) {
                                this.userList[i].createtime = this.userList[i].createtime.substring(0, 10);
                                this.userList[i].updatetime = this.userList[i].updatetime.substring(0, 10);
                            }
                        }
                    }).catch((err) => {
                        console.log(err);
                    });
            }
        },
        resetPassword(id) {
            this.$axios.get("/user/resetPassword/" + id)
                .then((result) => {
                    this.$message({
                        type: 'success',
                        message: result.data.message
                    });
                    if (result.data.code == 200) {
                        this.showList();
                        for (let i = 0; i < this.userList.length; i++) {
                            this.userList[i].createtime = this.userList[i].createtime.substring(0, 10);
                            this.userList[i].updatetime = this.userList[i].updatetime.substring(0, 10);
                        }
                    }
                }).catch((err) => {
                    console.log(err);
                })
        },
        setUstate(id) {
            this.$axios.get("/user/setState/" + id)
                .then((result) => {
                    this.$message({
                        type: 'success',
                        message: result.data.message
                    });
                    if (result.data.code == 200) {
                        this.showList();
                    }
                }).catch((err) => {
                    console.log(err);
                })
        },
        deleteOne(id) {
            this.$confirm('此操作将永久删除该用户, 是否继续?', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get("/user/deleteOne/" + id)
                    .then((result) => {
                        if (result.data.code == 200) {
                            this.$message({
                                type: 'success',
                                message: result.data.message
                            });
                            this.showList();
                        } else {
                            this.$message.error(result.data.message);
                        }
                    }).catch((err) => {
                        console.log(err);
                    });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '操作已取消'
                });
            });
        },
        handleSelectionChange(val) {
            this.checkList = val;
        },
        deleteSome() {
            let ids = [];
            for (let i = 0; i < this.checkList.length; i++) {
                ids.push(this.checkList[i].id);
            }
            if (this.checkList.length > 0) {
                this.$confirm('此操作将永久删除这些用户, 是否继续?', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.get("/user/deleteSome/" + ids)
                        .then((result) => {
                            if (result.data.code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.data.message
                                });
                                this.showList();
                            } else {
                                this.$message.error(result.data.message);
                            }
                        }).catch((err) => {
                            console.log(err);
                        });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '操作已取消'
                    });
                });
            } else {
                this.$message({
                    type: 'warning',
                    message: '请至少选择一项'
                });
            }
        },
        handleCurrentChange(val) {
            this.pageInfo.pageNum = val;
            this.showList();
        },
        handleSizeChange(val) {
            this.pageInfo.pageSize = val;
            this.showList();
        },
        showList() {
            this.$axios.get("/user?pageNum=" + this.pageInfo.pageNum + "&pageSize=" + this.pageInfo.pageSize)
                .then((result) => {
                    if (result.data.code == 200) {
                        this.pageInfo = result.data.data;
                        this.userList = result.data.data.list;
                        for (let i = 0; i < this.userList.length; i++) {
                            this.userList[i].createtime = this.userList[i].createtime.substring(0, 10);
                            this.userList[i].updatetime = this.userList[i].updatetime.substring(0, 10);
                        }
                    }
                }).catch((err) => {
                    console.log(err);
                });
        }
    },
    mounted() {
        this.showList();
        this.$axios.get("/role")
            .then((result) => {
                if (result.data.code == 200) {
                    this.roleList = result.data.data.list;
                }
            }).catch((err) => {
                console.log(err);
            });
    },
};
</script>

<style>
.pagination {
    text-align: left;
}
</style>
